package hn.cch.kafka;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;
import org.apache.kafka.common.serialization.StringSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Properties;
import java.util.concurrent.Future;

public class ProducerRunnable implements Runnable {

    private static final Logger logger = LoggerFactory.getLogger(ProducerRunnable.class);

    private String server;
    private String topic;

    public ProducerRunnable() {
    }

    public ProducerRunnable(String server, String topic) {
        this.server = server;
        this.topic = topic;
    }

    public String getServer() {
        return server;
    }

    public void setServer(String server) {
        this.server = server;
    }

    public String getTopic() {
        return topic;
    }

    public void setTopic(String topic) {
        this.topic = topic;
    }

    @Override
    public void run() {
        Properties properties =  new Properties();
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, server);
        // 序列化
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);

        // // 确认机制
        // properties.put(ProducerConfig.ACKS_CONFIG, "-1");
        // // 重试次数
        // properties.put(ProducerConfig.RETRIES_CONFIG, "0");
        // // 批量处理
        // properties.put(ProducerConfig.BATCH_SIZE_CONFIG, "16384");
        // // 等待时间
        // properties.put(ProducerConfig.LINGER_MS_CONFIG, "0");
        // // 缓冲内存
        // properties.put(ProducerConfig.BUFFER_MEMORY_CONFIG, "33554432");

        // 分区器
        // properties.put(ProducerConfig.PARTITIONER_CLASS_CONFIG, "hn.cch.custom.CustomPartitioner");
        // 生产者拦截器
        // properties.put(ProducerConfig.INTERCEPTOR_CLASSES_CONFIG, "hn.cch.custom.CustomProducerInterceptor");

        try (KafkaProducer<String, String> kafkaProducer = new KafkaProducer<>(properties)) {
            for (int i = 0; i < 10; i++) {
                ProducerRecord<String, String> producerRecord = new ProducerRecord<>(topic, "i", String.valueOf(i));
                Future<RecordMetadata> future = kafkaProducer.send(producerRecord);
                RecordMetadata recordMetadata = future.get();
                logger.info(recordMetadata.toString());
            }
        } catch (Exception e) {
            logger.info(e.getMessage());
        }
    }


}
